#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 文件名称: intervention.py
# 文件保存路径: backend/models/intervention.py
"""
干预记录数据模型 - 完整版本v5.0
按照技术文档B第4章标准完全重构
支持多种干预方式记录和Excel导入数据管理
新增累计统计字段和自动填充功能
"""

from sqlalchemy.orm import relationship
from datetime import datetime
from backend.infrastructure.database import db

class InterventionRecord(db.Model):
    """干预记录模型 - 完全符合技术文档B第4章标准v4.0"""
    __tablename__ = 'intervention_records'
    
    # ✅基础字段（技术文档B第4.2.1节）
    id = db.Column(db.Integer, primary_key=True, autoincrement=True, comment='记录ID')
    student_id = db.Column(db.Integer, db.ForeignKey('students.id', ondelete='CASCADE'), 
                       nullable=False, index=True, comment='学生ID')
    
    # ✅干预基础信息（技术文档B第4.2.2节）
    intervention_date = db.Column(db.Date, nullable=False, index=True, comment='干预日期')
    operation_time = db.Column(db.Time, nullable=True, comment='操作时间')
    intervention_type = db.Column(db.String(50), nullable=False, default='耳穴压丸', 
                             comment='干预方式：耳穴压丸/刮痧/艾灸/中药熏蒸/热灸训练/热磁脉冲/拔罐')
    operator = db.Column(db.String(50), nullable=True, comment='操作医生')
    duration_minutes = db.Column(db.Integer, nullable=True, comment='操作持续时间(分钟)')
    
    # ✅干预操作详情（技术文档B第4.2.4节）
    operation_location = db.Column(db.String(100), nullable=True, comment='操作地点')
    operation_tools = db.Column(db.JSON, nullable=True, comment='操作工具(JSON数组)')
    consumed_materials = db.Column(db.JSON, nullable=True, comment='消耗材料(JSON数组)')
    operation_sites = db.Column(db.JSON, nullable=True, comment='操作部位(JSON数组)')
    
    # ✅耳穴压丸专用字段（技术文档B第4.2.5节）
    acupoints = db.Column(db.JSON, nullable=True, comment='穴位选择(JSON数组)')
    press_methods = db.Column(db.JSON, nullable=True, comment='贴压方式(JSON数组)')
    press_strength = db.Column(db.String(20), nullable=True, default='中度', 
                          comment='按压强度：轻度/中度/重度')
    press_frequency = db.Column(db.Integer, nullable=True, comment='按压频率(次/分钟)')
    
    # ✅家庭干预支持（技术文档B第4.2.6节）
    is_home_intervention = db.Column(db.Boolean, nullable=False, default=False, 
                                comment='是否家庭干预')
    home_operator = db.Column(db.String(50), nullable=True, comment='家长姓名')
    home_operator_relation = db.Column(db.String(20), nullable=True, 
                                  comment='家长关系：父亲/母亲/爷爷/奶奶/外公/外婆/其他')
    related_hospital_record_id = db.Column(db.Integer, nullable=True, 
                                      comment='关联的医院干预记录ID')
    home_intervention_day = db.Column(db.Integer, nullable=True, comment='家庭干预第几天')
    daily_frequency = db.Column(db.Integer, nullable=True, comment='当日操作次数')
    parent_feedback = db.Column(db.Text, nullable=True, comment='家长反馈')
    upload_source = db.Column(db.String(20), nullable=True, 
                         comment='数据来源标记：PC端/小程序')
    
    # ✅效果评估（技术文档B第4.2.7节）
    immediate_effect = db.Column(db.String(20), nullable=True, 
                            comment='即时效果：有效/无效/待观察')
    cooperation_level = db.Column(db.String(20), nullable=True, 
                             comment='配合程度：良好/一般/较差')
    patient_reaction = db.Column(db.JSON, nullable=True, 
                            comment='患者反应(JSON数组)：舒适/热感/轻微疼痛/其他')
    child_cooperation = db.Column(db.String(20), nullable=True, 
                             comment='孩子配合度：良好/一般/较差')
    daily_effect_rating = db.Column(db.Integer, nullable=True, 
                               comment='每日效果评价(1-5分)')
    
    # ✅操作记录和备注（技术文档B第4.2.8节）
    details = db.Column(db.Text, nullable=True, comment='操作记录/补充说明')
    student_feedback = db.Column(db.Text, nullable=True, comment='学生反馈')
    
    # ✅数据管理字段（技术文档B第4.2.9节）
    data_year = db.Column(db.String(4), nullable=True, index=True, comment='数据年份')
    is_imported = db.Column(db.Boolean, nullable=False, default=False, 
                        comment='是否为导入数据')
    import_source = db.Column(db.String(100), nullable=True, 
                         comment='导入来源：Excel导入_YYYY等')
    session_number = db.Column(db.Integer, nullable=True, 
                          comment='本年度干预次序')
    global_sequence = db.Column(db.Integer, nullable=True, 
                           comment='全局干预次序')
    
    # ✅扩展数据（技术文档B第4.2.10节）
    operation_data = db.Column(db.JSON, nullable=True, comment='操作扩展数据（JSON格式）')
    
    # ✅干预专用字段（技术文档B第4.2.11节）
    # 刮痧专用字段
    scraping_intensity = db.Column(db.String(20), nullable=True, comment='刮痧强度：轻度/中度/重度')
    scraping_direction = db.Column(db.String(20), nullable=True, comment='刮痧方向：顺经/逆经/横向')
    scraping_duration = db.Column(db.Integer, nullable=True, comment='刮痧持续时间(分钟)')
    skin_reaction = db.Column(db.String(50), nullable=True, comment='皮肤反应：红润/紫红/瘀斑/其他')
    
    # 艾灸专用字段
    moxibustion_type = db.Column(db.String(20), nullable=True, comment='艾灸类型：直接灸/间接灸/温和灸')
    temperature_level = db.Column(db.String(20), nullable=True, comment='温度等级：温热/微热/灼热')
    moxibustion_distance = db.Column(db.String(20), nullable=True, comment='艾灸距离：近距/中距/远距')
    heat_sensation = db.Column(db.String(50), nullable=True, comment='热感：舒适/温热/灼热/疼痛')
    
    # 中药熏蒸专用字段
    steam_temperature = db.Column(db.Integer, nullable=True, comment='熏蒸温度(℃)')
    medicine_formula = db.Column(db.String(100), nullable=True, comment='中药配方')
    steam_intensity = db.Column(db.String(20), nullable=True, comment='熏蒸强度：轻度/中度/重度')
    comfort_level = db.Column(db.String(20), nullable=True, comment='舒适度：舒适/一般/不适')
    
    # 热灸训练专用字段
    intensity_level = db.Column(db.String(20), nullable=True, comment='强度等级：低/中/高')
    treatment_mode = db.Column(db.String(20), nullable=True, comment='治疗模式：连续/间歇/脉冲')
    temperature_feedback = db.Column(db.String(50), nullable=True, comment='温度反馈：舒适/温热/灼热')
    training_effect = db.Column(db.String(50), nullable=True, comment='训练效果：良好/一般/较差')
    
    # 热磁脉冲专用字段
    pulse_frequency = db.Column(db.Integer, nullable=True, comment='脉冲频率(Hz)')
    magnetic_intensity = db.Column(db.String(20), nullable=True, comment='磁场强度：低/中/高')
    pulse_pattern = db.Column(db.String(20), nullable=True, comment='脉冲模式：连续/间歇/交替')
    sensation_feedback = db.Column(db.String(50), nullable=True, comment='感觉反馈：舒适/温热/刺痛')
    
    # 拔罐专用字段
    suction_strength = db.Column(db.String(20), nullable=True, comment='吸力强度：轻度/中度/重度')
    cupping_method = db.Column(db.String(20), nullable=True, comment='拔罐方法：火罐/气罐/真空罐')
    skin_color_change = db.Column(db.String(50), nullable=True, comment='皮肤颜色变化：红润/紫红/瘀斑')
    cupping_marks = db.Column(db.String(50), nullable=True, comment='拔罐痕迹：轻微/明显/严重')
    
    # ✅累计统计字段（技术文档B第4.3.1节）
    # 注意：以下字段用于记录各干预方式的累计次数，录入时自动累加
    guasha_count = db.Column(db.Integer, nullable=True, default=0, comment='刮痧累计次数')
    aigiu_count = db.Column(db.Integer, nullable=True, default=0, comment='艾灸累计次数')
    erxue_yawan_count = db.Column(db.Integer, nullable=True, default=0, comment='耳穴压丸累计次数')
    zhongyao_xunzheng_count = db.Column(db.Integer, nullable=True, default=0, comment='中药熏蒸累计次数')
    rejiu_training_count = db.Column(db.Integer, nullable=True, default=0, comment='热灸训练累计次数')
    reci_pulse_count = db.Column(db.Integer, nullable=True, default=0, comment='热磁脉冲累计次数')
    baoguan_count = db.Column(db.Integer, nullable=True, default=0, comment='拔罐累计次数')
    
    # ✅时间戳（技术文档B第4.2.11节）
    created_at = db.Column(db.DateTime, nullable=False, default=datetime.now, comment='创建时间')
    updated_at = db.Column(db.DateTime, nullable=False, default=datetime.now, 
                       onupdate=datetime.now, comment='更新时间')
    
    # ✅ 兼容性字段（保留原有字段，标记为废弃）
    # 注意：以下字段将在下一版本中删除，目前保留以确保兼容性
    date = db.Column(db.Date, nullable=True, comment='DEPRECATED: 使用intervention_date替代')
    guasha = db.Column(db.Boolean, nullable=True, default=False, comment='DEPRECATED: 刮痧')
    aigiu = db.Column(db.Boolean, nullable=True, default=False, comment='DEPRECATED: 艾灸')
    erxue_yawan = db.Column(db.Boolean, nullable=True, default=False, comment='DEPRECATED: 耳穴压丸')
    zhongyao_xunzheng = db.Column(db.Boolean, nullable=True, default=False, comment='DEPRECATED: 中药熏蒸')
    rejiu_training = db.Column(db.Boolean, nullable=True, default=False, comment='DEPRECATED: 热灸训练')
    reci_pulse = db.Column(db.Boolean, nullable=True, default=False, comment='DEPRECATED: 热磁脉冲')
    baoguan = db.Column(db.Boolean, nullable=True, default=False, comment='DEPRECATED: 拔罐')
    
    # ✅关系定义（技术文档B第4.2.12节）
    student = relationship("Student", back_populates="intervention_records")
    
    # ✅索引和约束（技术文档B第4.2.13节）
    __table_args__ = (
        # 防重复索引
        db.Index('ix_student_intervention_date', 'student_id', 'intervention_date'),
        # 干预类型查询索引
        db.Index('ix_intervention_type_date', 'intervention_type', 'intervention_date'),
        # 数据年份索引
        db.Index('ix_data_year_imported', 'data_year', 'is_imported'),
        # 家庭干预索引
        db.Index('ix_home_intervention', 'is_home_intervention', 'home_operator'),
        # 关联医院记录索引
        db.Index('ix_related_hospital_record', 'related_hospital_record_id'),
        {'comment': '干预记录表v5.0 - 完全符合技术文档B第4章标准，新增累计统计字段'}
    )
    
    def to_dict(self):
        """转换为字典格式 - v4.0标准版本"""
        return {
            # 基础信息
            'id': self.id,
            'student_id': self.student_id,
            'intervention_date': self.intervention_date.isoformat() if self.intervention_date else None,
            'operation_time': self.operation_time.isoformat() if hasattr(self.operation_time, 'isoformat') else str(self.operation_time) if self.operation_time else None,
            'intervention_type': self.intervention_type,
            'operator': self.operator,
            'duration_minutes': self.duration_minutes,
            
            # 操作详情
            'operation_location': self.operation_location,
            'operation_tools': self.operation_tools,
            'consumed_materials': self.consumed_materials,
            'operation_sites': self.operation_sites,
            
            # 耳穴压丸专用
            'acupoints': self.acupoints,
            'press_methods': self.press_methods,
            'press_strength': self.press_strength,
            'press_frequency': self.press_frequency,
            
            # 家庭干预
            'is_home_intervention': self.is_home_intervention,
            'home_operator': self.home_operator,
            'home_operator_relation': self.home_operator_relation,
            'related_hospital_record_id': self.related_hospital_record_id,
            'home_intervention_day': self.home_intervention_day,
            'daily_frequency': self.daily_frequency,
            'parent_feedback': self.parent_feedback,
            'upload_source': self.upload_source,
            
            # 效果评估
            'immediate_effect': self.immediate_effect,
            'cooperation_level': self.cooperation_level,
            'patient_reaction': self.patient_reaction,
            'child_cooperation': self.child_cooperation,
            'daily_effect_rating': self.daily_effect_rating,
            
            # 24个干预专用字段
            'scraping_intensity': self.scraping_intensity,
            'scraping_direction': self.scraping_direction,
            'scraping_duration': self.scraping_duration,
            'skin_reaction': self.skin_reaction,
            'moxibustion_type': self.moxibustion_type,
            'temperature_level': self.temperature_level,
            'moxibustion_distance': self.moxibustion_distance,
            'heat_sensation': self.heat_sensation,
            'steam_temperature': self.steam_temperature,
            'medicine_formula': self.medicine_formula,
            'steam_intensity': self.steam_intensity,
            'comfort_level': self.comfort_level,
            'intensity_level': self.intensity_level,
            'treatment_mode': self.treatment_mode,
            'temperature_feedback': self.temperature_feedback,
            'training_effect': self.training_effect,
            'pulse_frequency': self.pulse_frequency,
            'magnetic_intensity': self.magnetic_intensity,
            'pulse_pattern': self.pulse_pattern,
            'sensation_feedback': self.sensation_feedback,
            'suction_strength': self.suction_strength,
            'cupping_method': self.cupping_method,
            'skin_color_change': self.skin_color_change,
            'cupping_marks': self.cupping_marks,
            
            # 操作记录
            'details': self.details,
            'student_feedback': self.student_feedback,
            
            # 数据管理
            'data_year': self.data_year,
            'is_imported': self.is_imported,
            'import_source': self.import_source,
            'session_number': self.session_number,
            'global_sequence': self.global_sequence,
            'operation_data': self.operation_data,
            
            # 累计统计字段
            'guasha_count': self.guasha_count,
            'aigiu_count': self.aigiu_count,
            'erxue_yawan_count': self.erxue_yawan_count,
            'zhongyao_xunzheng_count': self.zhongyao_xunzheng_count,
            'rejiu_training_count': self.rejiu_training_count,
            'reci_pulse_count': self.reci_pulse_count,
            'baoguan_count': self.baoguan_count,
            
            # 时间戳
            'created_at': self.created_at.isoformat() if self.created_at is not None else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at is not None else None,
            
            # 兼容性字段（标记为废弃）
            'date': self.date.isoformat() if self.date is not None else None,
            'guasha': self.guasha,
            'aigiu': self.aigiu,
            'erxue_yawan': self.erxue_yawan,
            'zhongyao_xunzheng': self.zhongyao_xunzheng,
            'rejiu_training': self.rejiu_training,
            'reci_pulse': self.reci_pulse,
            'baoguan': self.baoguan
        }
    
    def __repr__(self):
        return f'<InterventionRecord {self.id}: Student{self.student_id} - {self.intervention_type} on {self.intervention_date} @ {self.operation_location or "未知地点"}>'
    
    def get_intervention_config(self):
        """获取当前干预方式的配置信息（与新配置系统集成）"""
        try:
            # 修改：使用新的config_manager系统
            from backend.config.config_manager import ConfigManager
            config_manager = ConfigManager()
            return config_manager.get_intervention_api_defaults()
        except ImportError:
            # 如果新配置系统不可用，返回基本配置
            return {
                "display_name": self.intervention_type,
                "home_intervention_support": self.intervention_type == "耳穴压丸"
            }
    
    def validate_intervention_data(self):
        """验证干预数据的完整性和一致性"""
        errors = []
        
        # 基本验证
        if self.intervention_type is None or not self.intervention_type:
            errors.append("干预方式不能为空")
        
        if self.intervention_date is None:
            errors.append("干预日期不能为空")
        
        # 家庭干预验证
        if self.is_home_intervention:
            if self.home_operator is None or not self.home_operator:
                errors.append("家庭干预必须指定家长姓名")
            if self.related_hospital_record_id is None:
                errors.append("家庭干预必须关联医院记录")
        
        # 耳穴压丸专用验证
        if self.intervention_type == "耳穴压丸":
            if self.press_frequency is not None and (self.press_frequency < 30 or self.press_frequency > 120):
                errors.append("按压频率应在30-120次/分钟范围内")
        
        return errors
    
    def update_cumulative_counts(self):
        """更新累计统计字段（根据当前干预类型累加对应计数）"""
        # 根据intervention_type累加对应的计数字段
        if self.intervention_type == "刮痧":
            self.guasha_count = (self.guasha_count or 0) + 1
        elif self.intervention_type == "艾灸":
            self.aigiu_count = (self.aigiu_count or 0) + 1
        elif self.intervention_type == "耳穴压丸":
            self.erxue_yawan_count = (self.erxue_yawan_count or 0) + 1
        elif self.intervention_type == "中药熏蒸":
            self.zhongyao_xunzheng_count = (self.zhongyao_xunzheng_count or 0) + 1
        elif self.intervention_type == "热灸训练":
            self.rejiu_training_count = (self.rejiu_training_count or 0) + 1
        elif self.intervention_type == "热磁脉冲":
            self.reci_pulse_count = (self.reci_pulse_count or 0) + 1
        elif self.intervention_type == "拔罐":
            self.baoguan_count = (self.baoguan_count or 0) + 1
    
    def auto_fill_fields(self):
        """自动填充字段（录入时自动设置）"""
        # 自动设置数据年份
        if self.intervention_date is not None:
            # 处理日期格式转换
            if isinstance(self.intervention_date, str):
                try:
                    from datetime import datetime
                    date_obj = datetime.strptime(self.intervention_date, '%Y-%m-%d').date()
                    self.intervention_date = date_obj
                except ValueError:
                    pass  # 如果转换失败，保持原值
            
            # 设置数据年份
            if hasattr(self.intervention_date, 'year') and not isinstance(self.intervention_date, str):
                self.data_year = str(self.intervention_date.year)
        
        # 自动设置数据来源
        if self.upload_source is None or not self.upload_source:
            self.upload_source = 'PC端'
        
        # 更新累计统计
        self.update_cumulative_counts()
    
    def sync_deprecated_fields(self):
        """同步废弃字段（确保向后兼容性）"""
        # 同步日期字段
        if self.intervention_date is not None and self.date is None:
            self.date = self.intervention_date
        elif self.date is not None and self.intervention_date is None:
            self.intervention_date = self.date
        
        # 根据intervention_type设置相应的布尔字段
        # 清除所有布尔字段
        self.guasha = False
        self.aigiu = False
        self.erxue_yawan = False
        self.zhongyao_xunzheng = False
        self.rejiu_training = False
        self.reci_pulse = False
        self.baoguan = False
        
        # 设置对应的布尔字段
        if self.intervention_type == "刮痧":
            self.guasha = True
        elif self.intervention_type == "艾灸":
            self.aigiu = True
        elif self.intervention_type == "耳穴压丸":
            self.erxue_yawan = True
        elif self.intervention_type == "中药熏蒸":
            self.zhongyao_xunzheng = True
        elif self.intervention_type == "热灸训练":
            self.rejiu_training = True
        elif self.intervention_type == "热磁脉冲":
            self.reci_pulse = True
        elif self.intervention_type == "拔罐":
            self.baoguan = True
            self.aigiu = True
        elif self.intervention_type == "耳穴压丸":
            self.erxue_yawan = True
        elif self.intervention_type == "中药熏蒸":
            self.zhongyao_xunzheng = True
        elif self.intervention_type == "热灸训练":
            self.rejiu_training = True
        elif self.intervention_type == "热磁脉冲":
            self.reci_pulse = True
        elif self.intervention_type == "拔罐":
            self.baoguan = True
